// 应用处理类
import { DB_NAME, DB_PATH } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/config/dbconfig';
import { openSqlite  } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/SqliteHelper';
import { setupBackButtonHandler } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/app/backButtonHandler';
import { TableInit } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/TableInit';
import { AppConfig } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/model/AppConfig';
import { ApplicationServiceImpl } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/impl/ApplicationServiceImpl';
import { StringUtils } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/utils/StringUtils'

const applicationService = new ApplicationServiceImpl();
/**
 * APP打开处理
 * @return 
 */
export async function appOpen() {
	console.log("-----------------------");
	try {
		// 打开数据库
		await openSqlite(DB_NAME, DB_PATH);
	} catch (error) {
		console.error('Failed to open database:', error);
	}
	// 退出应用处理
	setupBackButtonHandler()
}





/**
 * 初始化业务数据库
 * @param {string} dbName
 * @return 数据库存储路径
 */
export async function initDb(dbName : string) : Promise<string>{
	try {
		const application = await applicationService.getApplicationByDbName(dbName)
		if (application) {
			return application.dbPath;
		} else {
			// 打开数据库，没有则新建
			return await openSqlite(dbName);
		}
	} catch (error) {
		console.error('Failed to init database:', error);
		throw error;
	}
}

/**
 * 初始化主数据库，并open所有的数据库
 * @return
 */
export async function initMainDbAndOpenAllDb(dbName : string) {
	console.log("------------initMainDbAndOpenAllDb-----------");
	try {
		if (StringUtils.isEmpty(dbName)) {
			dbName = 'main'
		}
		// 打开main数据库
		const dbPath = await openSqlite(dbName, DB_PATH);
		// 创建数据源配置表
		TableInit.tableInit(AppConfig);

		const hasMainApplication = await applicationService.hasApplication(dbName)

		if (!hasMainApplication) {
			// 添加main数据源配置
			const mainDb = new AppConfig()
			mainDb.code = dbName
			mainDb.name = '主应用'
			mainDb.dbName = dbName
			mainDb.dbPath = dbPath
			mainDb.description = dbName + '数据源'
			mainDb.createdDate = new Date()
			mainDb.version = '1.0'
			mainDb.url = ''
			await applicationService.insertApplication(mainDb)
		}


		// 获取所有数据源并打开
		const dbs = await applicationService.getApplications()
		dbs.forEach(db => {
			openSqlite(db.dbName, db.dbPath)
		})
	} catch (error) {
		console.error('Failed to open database:', error);
	}
	// 退出应用处理
	setupBackButtonHandler()
}